from flask import Flask, request, jsonify
import os
import tempfile
from run_eval import evaluate_pronunciation
import numpy as np

app = Flask(__name__)

@app.route('/eval', methods=['POST'])
def eval_pronunciation():
    # 获取参数
    if 'audio' not in request.files or 'text' not in request.form:
        return jsonify({'error': '请上传音频文件(audio)和参考文本(text)'}), 400

    audio_file = request.files['audio']
    reference_text = request.form['text']
    lang = request.form.get('lang', 'en')

    # 保存临时音频文件
    with tempfile.NamedTemporaryFile(delete=False, suffix='.wav') as tmp:
        audio_file.save(tmp)
        tmp_path = tmp.name

    # 调用评估
    try:
        result = evaluate_pronunciation(tmp_path, reference_text, lang)
        os.remove(tmp_path)
        if result is None:
            return jsonify({'error': '评估失败'}), 500
        # 递归转换所有numpy类型为Python内置类型
        def to_builtin_type(obj):
            if isinstance(obj, dict):
                return {k: to_builtin_type(v) for k, v in obj.items()}
            elif isinstance(obj, list):
                return [to_builtin_type(v) for v in obj]
            elif isinstance(obj, np.generic):
                return obj.item()
            else:
                return obj
        result = to_builtin_type(result)
        # 只返回核心JSON
        return jsonify(result)
    except Exception as e:
        os.remove(tmp_path)
        return jsonify({'error': str(e)}), 500

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5001)
